package com.example.live.view

import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.example.base.app.RouterPath
import com.example.common.mvi.BaseMviFragment
import com.example.live.R
import com.example.live.adapter.LiveAdapter
import com.example.live.databinding.FragmentLiveBinding
import com.example.live.intent.LiveViewIntent
import com.example.live.state.LiveUiState
import com.example.live.vm.LiveViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RouterPath.PATH_LIVE_PAGE)
@AndroidEntryPoint
class LiveFragment : BaseMviFragment<FragmentLiveBinding>() {

    override fun getLayoutId(): Int = R.layout.fragment_live

    private val mViewModel: LiveViewModel by activityViewModels()
    lateinit var liveAdapter : LiveAdapter
    private var mPosition = 0

    override fun initViews() {
        liveAdapter=LiveAdapter()
        mDataBinding.rvLive.adapter= liveAdapter
        //添加PageSnaphelper,实现翻页效果
        val helper = PagerSnapHelper()
        helper.attachToRecyclerView(mDataBinding.rvLive)
        val manager = LinearLayoutManager(requireContext())
        mDataBinding.rvLive.layoutManager = manager
        //获取适配器id
        liveAdapter.addChildClickViewIds(R.id.go_live)
        liveAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.go_live->{
                    ARouter.getInstance().build(RouterPath.PATH_LIVE_ROOM_PAGE)
                        .withSerializable("video",liveAdapter.getItem(position))
                        .navigation()
                }
            }
        }

        //给列表添加监听器
        mDataBinding.rvLive.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            /**
             * 滚动状态发生改变时回调
             */
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                //滑动列表，视频暂停，暂停滑动，播放当前视频
                if(newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    liveAdapter.shop()
                }else if(newState == RecyclerView.SCROLL_STATE_SETTLING){
                    liveAdapter.start()
                }
            }
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 获取当前可见的第一个和最后一个item位置
                val firstVisiblePosition = manager.findFirstVisibleItemPosition()
                val lastVisiblePosition = manager.findLastVisibleItemPosition()

                // 设置当前播放位置（通常是第一个完全可见的item）
                liveAdapter.setCurrentPosition(firstVisiblePosition)

                // 预加载当前视频的后两个视频
                if (lastVisiblePosition + 2 < liveAdapter.itemCount) {
                    liveAdapter.preloadNext(lastVisiblePosition + 1)
                }
            }
        })
        lifecycleScope.launch {
            mViewModel.channel.send(LiveViewIntent.LoadRecommendSimpleVideo(1,20))
        }
    }

    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiStateFlow.collect{
            when(it){
                is LiveUiState.LoadSimpleVideoSuccess -> {
                    liveAdapter.start()
                    liveAdapter.setResume(false)//未恢复状态
                    liveAdapter.addData(it.list)
                    liveAdapter.notifyDataSetChanged()
                }
                else->{}
            }
        }
    }
    //页面不显示暂停播放
    override fun onStop() {
        super.onStop()
        liveAdapter.setResume(true)
    }
    override fun onPause() {
        super.onPause()
        liveAdapter.release()//释放视频资源
        liveAdapter.shop()
    }

    override fun onResume() {
        super.onResume()
        liveAdapter.setResume(true)
        liveAdapter.notifyDataSetChanged()
    }
}